package com.chb.interceptor;

import com.alibaba.fastjson.JSON;
import com.chb.base.UserInfo;
import com.chb.common.CommonConstants;
import com.chb.utils.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author chenxiaoyu
 */
@Slf4j
public class HeaderInterceptor implements HandlerInterceptor {

    /**
     * 视图渲染之后的操作
     * @param request
     * @param response
     * @param arg2
     * @param arg3
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) {

    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     * @param request
     * @param response
     * @param arg2
     * @param arg3
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) {
        UserInfoContext.remove();
    }

    /**
     * 进入controller层之前拦截请求
     * @param request
     * @param response
     * @param obj
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) {
        String userInfoStr = request.getHeader(CommonConstants.USER_INFO_HEADER_NAME);
        if (StringUtils.isNotBlank(userInfoStr)) {
            UserInfoContext.setUserInfo(JSON.parseObject(URLDecoder.decode(userInfoStr, StandardCharsets.UTF_8), UserInfo.class));
        }
        return true;
    }

}
